package com.osmino.contacts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

public final class PhoneStateBroadcastReceiver extends BroadcastReceiver {

	private final ContactsPageActivity mController;
	private int mLastPhoneState;

	public PhoneStateBroadcastReceiver(ContactsPageActivity controller) {
		mController = controller;
		TelephonyManager telephonyManager = (TelephonyManager) mController
				.getSystemService(Context.TELEPHONY_SERVICE);
		mLastPhoneState = telephonyManager.getCallState();
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) {
			mController.onOutgoingCall();
		} else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())) {
			String key = TelephonyManager.EXTRA_STATE;
			int phoneState = intent.getIntExtra(key, mLastPhoneState);
			if (mLastPhoneState != phoneState) {
				if (mLastPhoneState == TelephonyManager.CALL_STATE_RINGING) {
					mController.onEndCall();
				}
				mLastPhoneState = phoneState;
			}
		}
	}
}
